package com.emisky.pictures.servlet;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.geometry.Positions;

import com.alibaba.druid.util.IOUtils;
import com.emisky.pictures.common.CommonUtils;
import com.emisky.pictures.common.PictureHelper;
import com.emisky.pictures.common.RequestWrapper;
import com.emisky.pictures.common.exception.PictureException;
import com.emisky.pictures.entity.PictureEntity;
import com.emisky.pictures.entity.WaterMarkEntity;

/**
 * 缩略图Servlet
 * Servlet implementation class ThumServlet
 */
public class ThumServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private PictureHelper _pictureHelper=null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ThumServlet() {
        super();
        _pictureHelper=CommonUtils.buildPictureHelper();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestWrapper requestWrapper=new RequestWrapper(request);
		String guid=requestWrapper.getParameter("guid");
		PictureEntity picture= this._pictureHelper.getPictureByGuid(guid);
		if(picture==null){
			throw new PictureException(guid+"未找到guid对应的Picture");
		}
		
		int width =Integer.parseInt(requestWrapper.getParameter("width","800"));
		int height=Integer.parseInt(requestWrapper.getParameter("height",String.valueOf(picture.getHeight())));
		
		Builder<? extends InputStream> builder= Thumbnails.of(new ByteArrayInputStream(picture.getBinaryData()));
		if(picture.getIswatermark()==1){
			//添加水印
			WaterMarkEntity waterMark=this._pictureHelper.getWaterMark(picture.getSiteKey());
			if(waterMark!=null){
				ByteArrayOutputStream bout=new ByteArrayOutputStream();
				int location=Integer.parseInt(waterMark.getLocation());	
				builder.watermark(
						CommonUtils.getPosition(location,Positions.BOTTOM_RIGHT), 
						ImageIO.read(new File(waterMark.getWatermarkpath())), 
						Float.parseFloat(waterMark.getOpacity())).size(picture.getWidth(), picture.getHeight()).toOutputStream(bout);
			
				builder=Thumbnails.of(new ByteArrayInputStream(bout.toByteArray()));
			}
		}
		if(width!=0 && height!=0 && picture.getIsthum()==1){
			//缩略图
			builder=builder.size(width,height);
		}else{
			builder=builder.size(picture.getWidth(),picture.getHeight());
		}
		builder.toOutputStream(response.getOutputStream());
	}

}
